package ai.mspbots.poc.controller.v2;

import ai.mspbots.poc.db.service.SysReportService;
import ai.mspbots.poc.es.entity.ReportDocument;
import ai.mspbots.poc.es.service.ElasticsearchSaveService;
import ai.mspbots.poc.help.PocEnv;
import ai.mspbots.poc.help.VectorHelper;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.cpu.nativecpu.NDArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RequestMapping("/v2/init")
@RestController
public class InitController {

    private static final Logger logger = LoggerFactory.getLogger(InitController.class);
    private static final String INDEX_NAME = SpringUtil.getBean(PocEnv.class).getIndex();
    @Autowired
    private SysReportService sysReportService;

    @Autowired
    private ElasticsearchSaveService elasticsearchSaveService;
    /**
     * 初始化es索引
     */
    @PostMapping("/es")
    public void initEsIndex() {
        List<ReportDocument> reportDocuments = sysReportService.selectReportDocumentList(1, -1);
        logger.info("reportDocuments.size() = {}", reportDocuments.size());
        for (ReportDocument reportDocument : reportDocuments) {
            logger.info("reportDocument = {}", reportDocument);
            String name = reportDocument.getName();
            INDArray nameArray = new NDArray();
            if (StrUtil.isNotEmpty(name)) {
                nameArray = VectorHelper.vectorizedText(name);
            }

            String description = reportDocument.getDescription();
            INDArray descriptionArray = new NDArray();
            if (StrUtil.isNotEmpty(description)) {
                descriptionArray = VectorHelper.vectorizedText(description);
            }
            elasticsearchSaveService.saveToElasticsearch(INDEX_NAME,
                    String.valueOf(reportDocument.getId()),
                    name,
                    description,
                    nameArray,
                    descriptionArray);
        }
    }
}
